package com.cherrypt.api.core.service.impl;

import com.cherrypt.api.common.enums.ResultEnum;
import com.cherrypt.api.common.exception.TipException;
import com.cherrypt.api.core.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ValueOperations<String, Object> valueOperations;

    @Value("${api.config.redis.captcha.prefix}")
    private String captchaPrefix;

    @Value("${api.config.redis.captcha.exp}")
    private long captchaExp;

    @Value("${api.config.redis.ipCount.prefix}")
    private String ipCountPrefix;

    @Value("${api.config.redis.ipCount.exp}")
    private long ipCountExp;

    @Override
    public void saveCaptcha(String ip, String captcha) throws TipException {
        if (StringUtils.isBlank(captcha)) {
            throw new TipException(ResultEnum.CAPTCHA_EMPTY_ERROR);
        }
        valueOperations.set(captchaPrefix + ip, captcha, Duration.ofSeconds(captchaExp));
    }

    @Override
    public boolean removeCaptcha(String ip) {
        return redisTemplate.delete(captchaPrefix + ip);
    }

    @Override
    public boolean verifyCaptcha(String ip, String captcha) throws TipException {
        if (StringUtils.isBlank(captcha)) {
            throw new TipException(ResultEnum.CAPTCHA_EMPTY_ERROR);
        }
        if (captcha.length() != 4) {
            throw new TipException(ResultEnum.CAPTCHA_FORMAT_ERROR);
        }
        String verifyCaptcha = (String) valueOperations.get(captchaPrefix + ip);
        return StringUtils.isNotBlank(verifyCaptcha) && verifyCaptcha.equals(captcha.toUpperCase());
    }

    @Override
    public void incrIp(String ip, String name) {
        redisTemplate.expire(ipCountPrefix + ip + name, ipCountExp, TimeUnit.SECONDS);
    }

    @Override
    public boolean verifyIp(String ip, String name, int count) {
        int sum;
        String value = (String) valueOperations.get(ipCountPrefix + ip + name);
        if (value == null) {
            sum = 1;
        } else {
            sum = Integer.parseInt(value);
        }
        return sum <= count;
    }
}
